package com.pro01.backend.service;

import com.pro01.backend.dto.UserRatioDTO;
import com.pro01.backend.mapper.RatioMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RatioService {

    @Autowired
    private RatioMapper ratioMapper;

    public UserRatioDTO getUserRatio(Long userId) {
        Long downloadTotal = ratioMapper.sumDownloadByUser(userId);
        Long uploadTotal = ratioMapper.estimateUploadByUploader(userId);

        if (downloadTotal == null) downloadTotal = 0L;
        if (uploadTotal == null) uploadTotal = 0L;

        double ratio = downloadTotal == 0 ? (uploadTotal > 0 ? 999.0 : 0.0)
                : (double) uploadTotal / downloadTotal;

        UserRatioDTO dto = new UserRatioDTO();
        dto.setUploadTotal(uploadTotal);
        dto.setDownloadTotal(downloadTotal);
        dto.setShareRatio(Math.round(ratio * 100.0) / 100.0); // 保留两位小数

        return dto;
    }

    public UserRatioDTO getUserRewardedRatio(Long userId) {
        // 原始数据
        Long realDownload = ratioMapper.sumDownloadByUser(userId);
        Long realUpload = ratioMapper.estimateUploadByUploader(userId);
        if (realDownload == null) realDownload = 0L;
        if (realUpload == null) realUpload = 0L;

        // 奖励数据
        Long rewardUpload = ratioMapper.sumRewardUploaded(userId);
        Long rewardDownload = ratioMapper.sumRewardDownloaded(userId);
        if (rewardUpload == null) rewardUpload = 0L;
        if (rewardDownload == null) rewardDownload = 0L;

        long virtualUpload = realUpload + rewardUpload;
        long virtualDownload = Math.max(1, realDownload - rewardDownload);

        // ✅ 新用户保护逻辑：如果上传下载全是 0，默认分享率 = 1.0
        if (virtualUpload == 0 && realDownload == 0 && rewardDownload == 0) {
            UserRatioDTO dto = new UserRatioDTO();
            dto.setUploadTotal(0L);
            dto.setDownloadTotal(0L);
            dto.setShareRatio(1.0);
            return dto;
        }
        double ratio = (double) virtualUpload / virtualDownload;

        UserRatioDTO dto = new UserRatioDTO();
        dto.setUploadTotal(virtualUpload);
        dto.setDownloadTotal(virtualDownload);
        dto.setShareRatio(Math.round(ratio * 100.0) / 100.0);

        return dto;
    }

}

